package cn.pugle.oj.leetcode;

import cn.pugle.oj.catalog.DivideConquer;

import java.util.Arrays;

/**
 * https://labuladong.gitbook.io/algo/di-ling-zhang-bi-du-xi-lie/er-fen-cha-zhao-xiang-jie
 * <p>
 * https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/
 *
 * @author tzp
 * @since 2020/10/19
 */
public class LC34_1 implements DivideConquer {
    public int[] searchRange(int[] nums, int target) {
        return new int[]{left_bound(nums, target), right_bound(nums, target)};
    }

    int right_bound(int[] nums, int target) {
        int left = 0, right = nums.length - 1;
        while (left <= right) {
            int mid = left + (right - left) / 2;
            if (nums[mid] < target) {
                left = mid + 1;
            } else if (nums[mid] > target) {
                right = mid - 1;
            } else if (nums[mid] == target) {
                // 别返回，锁定右侧边界
                left = mid + 1;
            }
        }
        // 最后要检查 right 越界的情况
        if (right < 0 || nums[right] != target)
            return -1;
        return right;
    }

    int left_bound(int[] nums, int target) {
        int left = 0, right = nums.length - 1;
        while (left <= right) {
            int mid = left + (right - left) / 2;
            if (nums[mid] < target) {
                left = mid + 1;
            } else if (nums[mid] > target) {
                right = mid - 1;
            } else if (nums[mid] == target) {
                // 别返回，锁定左侧边界
                right = mid - 1;
            }
        }
        // 最后要检查 left 越界的情况
        if (left >= nums.length || nums[left] != target) {
            return -1;
        }
        return left;
    }


    public static void main(String[] args) {
        System.out.println(Arrays.toString(new LC34_1().searchRange(new int[]{5, 7, 7, 8, 8, 10}, 3)));
        System.out.println(Arrays.toString(new LC34_1().searchRange(new int[]{7, 7, 7, 8, 8, 10}, 7)));
        System.out.println(Arrays.toString(new LC34_1().searchRange(new int[]{7, 7, 7, 8, 8, 10}, 9)));
        System.out.println(Arrays.toString(new LC34_1().searchRange(new int[]{7, 7, 7, 8, 8, 10}, 11)));
    }
}
